﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// IWMS出入站接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class InventoryInOutController : ControllerBase
    {
        private readonly ILogger<IWMS_InventoryInOutDto> _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_qh;


        public InventoryInOutController(ILogger<IWMS_InventoryInOutDto> logger,IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration)
        {
            _logger = logger;
            _WMSTokenCheckService = wmsTokenCheckService;
             con= _configuration.GetConnectionString("DDM_DbConnection_ZH");

        }

        /// <summary>
        /// IWMS出入库接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostIWMSInventory([FromBody] IWMS_InventoryInOutRequestDto strparm)
        {
            string  strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            IWMS_InventoryInOutRequestDto result = new IWMS_InventoryInOutRequestDto();
            IWMS_InventoryInOutResponseDto re = new IWMS_InventoryInOutResponseDto();
            string source_sys = strparm.source_sys;
            string inout_type = strparm.inout_type;
            string invent_date = strparm.invent_date;
            string carplace_code = strparm.carplace_code;
            string carframe_code= strparm.carframe_code;
            string carframe_sequence = strparm.carframe_sequence;
            string knife_number = strparm.knife_number;
            string source_no = strparm.source_no;


            try
            {

                if (source_sys.Trim() != "")
                {
                    if (invent_date.Trim() !="")
                    {
                        if (inout_type.Trim() != "")
                        {
                            if (source_sys.Trim() == "SDCADA")
                            {
                                if (inout_type.Trim()=="0")
                                {
                                    if (knife_number.Trim()!="")
                                    {
                                        strSqlList = new List<string>();
                                        strSql = new StringBuilder();
                                        strSql.Append("select * from stock_inventory where knife_number='" + knife_number + "' and del_flag='0' limit 1");
                                        DataTable dt_check_inventory = DB.Query(strSql.ToString(), con);
                                        if (dt_check_inventory.Rows.Count>0)
                                        {
                                            string kc_carplace_code = dt_check_inventory.Rows[0]["carplace_code"].ToString();
                                            string kc_carframe_code = dt_check_inventory.Rows[0]["carframe_code"].ToString();
                                            string kc_carframe_sequence = dt_check_inventory.Rows[0]["carframe_sequence"].ToString();
                                            string kc_carplace_name = dt_check_inventory.Rows[0]["carplace_name"].ToString();


                                            strSql = new StringBuilder();
                                            strSql.Append(@"select max(id) id,max(document_id) doid from stock_invent_item");
                                            DataTable dt_maxid_ls = DB.Query(strSql.ToString(), con);
                                            string maxid_ls = dt_maxid_ls.Rows[0]["id"].ToString().Trim();
                                            string doid_ls = dt_maxid_ls.Rows[0]["doid"].ToString().Trim();
                                            int i = 1;

                                            strSql = new StringBuilder();
                                            strSql.Append("INSERT INTO stock_invent_item  (id,document_id,status,tenant_id,form_id,owner,created_by,creation_date,last_updated_by,last_update_date,object_version_number," +
                                                "carplace_code, carframe_code, carframe_sequence, knife_number, inout_type, source_sys, invent_date,source_no,carplace_name) VALUES (" + maxid_ls + "+" + i + " ," + doid_ls + "+" + i + " ,'COMPLETED',  '339816648452079617', '63be11f996b76b5c4254f493',  '100340167064629018624', '100340167064629018624', SYSDATE()," +
                                                "'100340167064629018624',SYSDATE(), 1, '" + kc_carplace_code + "', '" + kc_carframe_code + "', '" + kc_carframe_sequence + "', '" + knife_number + "','出库', '" + source_sys + "', '" + invent_date + "','" + source_no + "','" + kc_carplace_name + "')");
                                            strSqlList.Add(strSql.ToString());

                                            strSql = new StringBuilder();
                                            strSql.Append(@"update stock_inventory set del_flag=1 where  knife_number='" + knife_number + "'  and carplace_code='"+ kc_carplace_code + "'  ");
                                            strSqlList.Add(strSql.ToString());

                                            if (strSqlList.Count > 0)
                                            {
                                                bool A = DB.ExecuteNoQueryTran(strSqlList, con);
                                                if (!A)
                                                {
                                                    strMsg = "更新数据出现问题，请联系IWMS管理员,SCADA同步失败";
                                                }
                                                else
                                                {
                                                    strSql = new StringBuilder();
                                                    strSql.Append("select * from interface_url_manage where function_description='脱胶后扫码解绑'");
                                                    DataTable dt_mes_lb = DB.Query(strSql.ToString(), con);
                                                    string mesurl = dt_mes_lb.Rows[0]["interface_url"].ToString();
                                                    IWMS_AGV_TJJBRequestDto AGVTJ = new IWMS_AGV_TJJBRequestDto();
                                                    AGVTJ.code = knife_number;
                                                    AGVTJ.stationCode = kc_carplace_code;                                       
                                                    string jsonText = JsonConvert.SerializeObject(AGVTJ);
                                                    var reAgv = DB.httpPost(mesurl, jsonText, "", "否");
                                                    IWMS_AGV_TJJBResponseDto psp = JsonConvert.DeserializeObject<IWMS_AGV_TJJBResponseDto>(reAgv);
                                                    if (psp.code == 500)
                                                    {
                                                        strMsg = "AGV返回异常："+ psp.message;
                                                    }

                                                }
                                            }
                                        }
                                        else
                                        {
                                            strMsg = "IWMS：找不到刀号《" + knife_number + "》的库存信息，请检查AGV是否进行了车位入站";
                                        }
                                    }
                                    else
                                    {
                                        strMsg = "SCADA脱胶上机，晶棒刀号不能传空";
                                    }
                                    

                                }
                                else
                                {
                                    strMsg = "当前SCADA出入库类型,不为入库类型，操作失败";
                                }
                            }
                            else if (source_sys.Trim() == "AGV")
                            {
                                strSql = new StringBuilder();
                                strSql.Append("select * from base_carplace where carplace_code='" + carplace_code + "' limit 1");
                                DataTable dt_check_carplace = DB.Query(strSql.ToString(), con);
                                if (dt_check_carplace.Rows.Count > 0)
                                {
                                    string carplace_name = dt_check_carplace.Rows[0]["carplace_name"].ToString();
                                    strSql = new StringBuilder();
                                    strSql.Append("select * from base_carframe where carframe_code='" + carframe_code + "' limit 1");
                                    DataTable dt_check_carframe = DB.Query(strSql.ToString(), con);
                                    if (dt_check_carframe.Rows.Count > 0)
                                    {
                                        //车架入库，固化空车入库、脱胶满车入库
                                        if (inout_type.Trim() == "1")
                                        {
                                            if (knife_number!="")
                                            {
                                                strSqlList = new List<string>();
                                                strSql = new StringBuilder();
                                                strSql.Append(@"select * from stock_inventory where knife_number='" + knife_number + "'");
                                                DataTable dt_knife_numbercheck = DB.Query(strSql.ToString(), con);
                                                if (dt_knife_numbercheck.Rows.Count > 0)
                                                {
                                                    strMsg = "刀号<" + knife_number + ">已存在车位绑定记录，请查询清楚后再入库";
                                                }
                                             
                                            }

                                            if (strMsg=="")
                                            {
                                                strSql = new StringBuilder();
                                                strSql.Append(@"select max(id) id,max(document_id) doid from stock_invent_item");
                                                DataTable dt_maxid_ls = DB.Query(strSql.ToString(), con);
                                                string maxid_ls = dt_maxid_ls.Rows[0]["id"].ToString().Trim();
                                                string doid_ls = dt_maxid_ls.Rows[0]["doid"].ToString().Trim();
                                                int i = 1;

                                                strSql = new StringBuilder();
                                                strSql.Append("INSERT INTO stock_invent_item  (id,document_id,status,tenant_id,form_id,owner,created_by,creation_date,last_updated_by,last_update_date,object_version_number," +
                                                "carplace_code, carframe_code, carframe_sequence, knife_number, inout_type, source_sys, invent_date,source_no,carplace_name) VALUES (" + maxid_ls + "+" + i + " ," + doid_ls + "+" + i + " ,'COMPLETED',  '339816648452079617', '63be11f996b76b5c4254f493',  '100340167064629018624', '100340167064629018624', SYSDATE()," +
                                                "'100340167064629018624',SYSDATE(), 1, '" + carplace_code + "', '" + carframe_code + "', '" + carframe_sequence + "', '" + knife_number + "','入库', '" + source_sys + "', '" + invent_date + "','" + source_no + "','" + carplace_name + "')");
                                                strSqlList.Add(strSql.ToString());


                                                strSql = new StringBuilder();
                                                strSql.Append(@"select max(id) id,max(document_id) doid from stock_inventory");
                                                DataTable dt_maxid_kc = DB.Query(strSql.ToString(), con);
                                                string maxid_kc = dt_maxid_ls.Rows[0]["id"].ToString().Trim();
                                                string doid_kc = dt_maxid_ls.Rows[0]["doid"].ToString().Trim();

                                                strSql = new StringBuilder();
                                                strSql.Append("INSERT INTO stock_inventory  (id,document_id,status,tenant_id,form_id,owner,created_by,creation_date,last_updated_by,last_update_date,object_version_number," +
                                                "carplace_code, carframe_code, carframe_sequence, knife_number,source_sys,invent_date,del_flag,carplace_name) VALUES (" + maxid_kc + "+" + i + " ," + doid_kc + "+" + i + " ,'COMPLETED',  '339816648452079617', '63be114696b76b5c4254f47f',  '100340167064629018624', '100340167064629018624', SYSDATE()," +
                                                "'100340167064629018624',SYSDATE(), 1, '" + carplace_code + "', '" + carframe_code + "', '" + carframe_sequence + "', '" + knife_number + "', '" + source_sys + "', '" + invent_date + "','0','" + carplace_name + "')");
                                                strSqlList.Add(strSql.ToString());


                                                if (strSqlList.Count > 0)
                                                {
                                                    bool A = DB.ExecuteNoQueryTran(strSqlList, con);
                                                    if (!A)
                                                    {
                                                        strMsg = "更新数据出现问题，请联系IWMS管理员";
                                                    }

                                                }
                                            }
                                                                                                                         
                                        }
                                        else if(inout_type.Trim() == "0")
                                        {
                                            string knife_number_list = "";
                                            strSqlList = new List<string>();
                                            strSql = new StringBuilder();
                                            strSql.Append(@"select * from stock_inventory where carplace_code='" + carplace_code + "'");
                                            DataTable dt_inventory_carplacecheck = DB.Query(strSql.ToString(), con);
                                            if (dt_inventory_carplacecheck.Rows.Count>0)
                                            {
                                                foreach (DataRow row in dt_inventory_carplacecheck.Rows)
                                                {
                                                    if (row["knife_number"].ToString()!="")
                                                    {
                                                        knife_number_list = knife_number_list + row["knife_number"].ToString()+",";
                                                    }
                                                    string kc_carframe_code = row["carframe_code"].ToString();
                                                    string kc_carframe_sequence = row["carframe_sequence"].ToString();
                                                    string kc_knife_number = row["knife_number"].ToString();
                                                    string kc_carplace_name = row["carplace_name"].ToString();


                                                    strSql = new StringBuilder();
                                                    strSql.Append(@"select max(id) id,max(document_id) doid from stock_invent_item");
                                                    DataTable dt_maxid_ls = DB.Query(strSql.ToString(), con);
                                                    string maxid_ls = dt_maxid_ls.Rows[0]["id"].ToString().Trim();
                                                    string doid_ls = dt_maxid_ls.Rows[0]["doid"].ToString().Trim();
                                                    int i = 1;

                                                    strSql = new StringBuilder();
                                                    strSql.Append("INSERT INTO stock_invent_item  (id,document_id,status,tenant_id,form_id,owner,created_by,creation_date,last_updated_by,last_update_date,object_version_number," +
                                                        "carplace_code, carframe_code, carframe_sequence, knife_number, inout_type, source_sys, invent_date,source_no,carplace_name) VALUES (" + maxid_ls + "+" + i + " ," + doid_ls + "+" + i + " ,'COMPLETED',  '339816648452079617', '63be11f996b76b5c4254f493',  '100340167064629018624', '100340167064629018624', SYSDATE()," +
                                                        "'100340167064629018624',SYSDATE(), 1, '" + carplace_code + "', '" + kc_carframe_code + "', '" + kc_carframe_sequence + "', '" + kc_knife_number + "','出库', '" + source_sys + "', '" + invent_date + "','" + source_no + "','" + kc_carplace_name + "')");
                                                    strSqlList.Add(strSql.ToString());

                                                    i++;
                                                }

                                                strSql = new StringBuilder();
                                                strSql.Append(@"update stock_inventory set del_flag=1 where   carplace_code='" + carplace_code + "' ");
                                                strSqlList.Add(strSql.ToString());

                                                knife_number = knife_number_list.Trim(',');

                                                if (strSqlList.Count > 0)
                                                {
                                                    bool A = DB.ExecuteNoQueryTran(strSqlList, con);
                                                    if (!A)
                                                    {
                                                        strMsg = "IWMS异常：更新数据出现问题，请联系IWMS管理员,AGV解绑同步失败";
                                                    }
                                                    else
                                                    {
                                                        strSql = new StringBuilder();
                                                        strSql.Append("select * from interface_url_manage where function_description='拉棒接口'");
                                                        DataTable dt_mes_lb = DB.Query(strSql.ToString(), con);
                                                        string mesurl = dt_mes_lb.Rows[0]["interface_url"].ToString();
                                                        IWMS_MESLBRequestDto MESLB = new IWMS_MESLBRequestDto();
                                                        MESLB.KnifeNumber = knife_number;
                                                        MESLB.WorkCenter = "切片一车间A区";
                                                        MESLB.Shift = "A";
                                                        MESLB.Employee = "AGV";
                                                        string jsonText = JsonConvert.SerializeObject(MESLB);
                                                        var reMES = DB.httpPost(mesurl, jsonText, "", "否");
                                                        IWMS_MESLBResponseDto psp = JsonConvert.DeserializeObject<IWMS_MESLBResponseDto>(reMES);
                                                        if (psp.Success == "false")
                                                        {
                                                            strMsg = "MES返回异常：" + psp.Message;
                                                        }

                                                    }
                                                }

                                            }
                                            else
                                            {
                                                strMsg = "车位《"+ carplace_code + "》不存在晶棒信息，请联脱胶人员进行车位刀号绑定";
                                            }
                                        }
                                    }
                                    else
                                    {
                                        strMsg = "车架编码<" + carframe_code + ">,不存在，请查询清楚";
                                    }
                                }
                                else
                                {
                                    strMsg = "点位编码<" + carplace_code + ">,不存在，请查询清楚";
                                }
                            }
                            else
                            {
                                strMsg = "来源系统《"+ source_sys.Trim() +"》不存在接口配置需求，请传'AGV'或'SCADA'";
                            }
                            
                        }
                        else
                        {
                            strMsg = "插入类型不能为空,1代表入站、0代表出站";
                        }
                    }
                    else
                    {
                        strMsg = "业务发生日期不能为空";
                    }
                   
                }
                else
                {
                    strMsg = "来源系统不能为空,SCADA或AGV";
                }
                   

            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

         


            if (strMsg=="")
            {
                re.status = "成功";
                re.code = "0";
                re.message = "";
            }
            else
            {
                re.status = "失败";
                re.code = "500";
                re.message = strMsg;
            }


            return new JsonResult(re);
        }

      



    }
}
